package com.yidu.finance.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ValicodeServlet
 */
@WebServlet("/ValicodeServlet")
public class ValicodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	public static final String Word = "qwertyuioplkjhgfdsazxcvbnm1234567890";
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		Random rd = new Random();
		
		response.setContentType("image/jpeg");
		OutputStream os = response.getOutputStream();
		
		BufferedImage image = new BufferedImage(175, 100, BufferedImage.TYPE_INT_BGR);
		
		Graphics g = image.getGraphics();
		g.setColor(new Color(181,242,138));//
		g.fillRect(0, 0, 175, 100);
		
		g.setFont(new Font("微软雅黑", Font.BOLD, 20));
		
		String code = "";
		for(int i=0;i<4;i++){
			char c = Word.charAt(rd.nextInt(Word.length()));
			g.setColor(new Color(rd.nextInt(255),rd.nextInt(255),rd.nextInt(255)));
			g.drawString(c+"", i*48, 60);
			code+=c;
		}
		System.out.println(code);
		HttpSession session = request.getSession();
		String sid = session.getId();
		System.out.println("当前的sessionID是："+sid);
		session.setAttribute("code", code);
		for(int i=0;i<10;i++){
			g.setColor(new Color(rd.nextInt(255),rd.nextInt(255),rd.nextInt(255)));	
			g.drawLine(rd.nextInt(175), rd.nextInt(100), rd.nextInt(175), rd.nextInt(100));
		}
		
		ImageIO.write(image, "JPEG", os);
		os.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}
